<template>
  <el-scrollbar :wrap-class="{ wrapClass: true }">
    <div class="app-container">
      <div class="filter-container">
        <el-input
          v-model="listQuery.title"
          :placeholder="$t('common.emailMarketingName')"
          style="width: 200px"
          class="filter-item"
          clearable
          @keyup.enter.native="handleFilter"
          size="small"
        />
        <date-selector
          v-model="listQuery.createdAt"
          type="daterange"
          style="width: 300px; vertical-align: middle"
          value-format="yyyy-MM-dd"
        />
        <el-select
          v-model="listQuery.state"
          :placeholder="$t('common.status')"
          clearable
          style="width: 120px"
          class="filter-item"
          size="small"
        >
          <el-option
            v-for="item in stateOptions"
            :key="item.key"
            :label="item.label"
            :value="item.key"
          />
        </el-select>
        <div style="display: inline-block; margin-right: 10px"></div>
        <el-button
          plain
          v-waves
          class="filter-item"
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="handleFilter"
        >
          {{ $t('table.search') }}
        </el-button>
        <el-button
          plain
          size="mini"
          class="filter-item"
          style="margin-left: 10px"
          type="warning"
          icon="el-icon-s-promotion"
          @click="createMarketingTaskByServer"
        >
          {{ $t('route.emailServerSend') }}
        </el-button>
        <el-button
          plain
          class="filter-item"
          style="margin-left: 10px"
          type="success"
          size="mini"
          icon="el-icon-s-promotion"
          @click="handleEmailSendFree"
        >
          {{ $t('route.emailSendFree') }}
        </el-button>
        <el-button
          plain
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          size="mini"
          icon="el-icon-magic-stick"
          @click="handleVerifyEmail"
        >
          {{ $t('email.validateEmailValidity') }}
        </el-button>
        <el-button
          size="small"
          class="filter-item right filter-left filter-refresh"
          icon="el-icon-refresh"
          type="primary"
          plain
          @click="refresh"
        >
          {{ $t('common.refresh') }}
        </el-button>
        <!-- <el-button
          v-waves
          :loading="downloadLoading"
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          @click="handleDownload"
        >
          {{ $t('table.export') }}
        </el-button> -->
        <!-- <el-button
          plain
          v-waves
          :loading="downloadLoading"
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          size="small"
          @click=""
        >
          批量删除
        </el-button>
        <el-button
          plain
          v-waves
          :loading="downloadLoading"
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          size="small"
          @click=""
        >
          回收站
        </el-button> -->
        <!-- <el-checkbox
          v-model="showReviewer"
          class="filter-item"
          style="margin-left:15px;"
          @change="tableKey=tableKey+1"
        >
          {{ $t('table.reviewer') }}
        </el-checkbox> -->
      </div>

      <el-table
        :data="list.items"
        border
        fit
        highlight-current-row
        style="width: 100%"
        :height="
          list.totalCount > 0 ? 'calc(100vh - 205px)' : 'calc(100vh - 170px)'
        "
      >
        <el-table-column align="center" width="50" type="index">
          <!-- sortable="custom" -->
          <!-- :class-name="getSortClass('id')" -->
        </el-table-column>

        <el-table-column
          :label="$t('common.emailMarketingName')"
          min-width="190px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span class="link-type" @click="handleShowSendDataTracking(row.id)">
              <el-tag type="primary">{{ row.title }}</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.type')"
          min-width="70px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span v-if="row.type === 'SERVER'">
              <el-tag effect="plain" type="warning">{{
                $t('email.server')
              }}</el-tag>
            </span>
            <span v-else>
              <el-tag effect="plain" type="success">{{
                $t('email.free')
              }}</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.status')"
          min-width="100px"
          align="center"
        >
          <template slot-scope="{ row }">
            <template v-for="item in stateOptions">
              <template v-if="item['key'] === row.state">
                <span :class="item.class" :key="item.key"
                  ><i :class="item.icon" />
                  {{ item.label }}
                </span>
              </template>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('email.submitNum')"
          min-width="70px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span class="count_icon">
              <i class="el-icon-message"
                ><span class="num-after-icon">{{ row.submitNum }}</span></i
              >
            </span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('email.sendNum')"
          min-width="70px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span class="count_icon">
              <i class="el-icon-s-promotion"
                ><span class="num-after-icon">{{ row.sendingNum }}</span></i
              >
            </span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('email.openNum')"
          min-width="70px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span class="count_icon">
              <svg
                t="1621230206287"
                class="icon"
                fill="#FF7908"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="2120"
                width="20"
                height="20"
              >
                <path
                  d="M896 992H128c-52.928 0-96-43.072-96-96V416a32 32 0 0 1 64 0v480c0 17.632 14.368 32 32 32h768c17.632 0 32-14.368 32-32V416a32 32 0 0 1 64 0v480c0 52.928-43.072 96-96 96z"
                  p-id="2121"
                ></path>
                <path
                  d="M64 448a32 32 0 0 1-19.808-57.152l124.608-97.92a32 32 0 1 1 39.584 50.336l-124.608 97.92A32 32 0 0 1 64 448zM350.304 223.04a32 32 0 0 1-19.808-57.152l161.696-127.04a32 32 0 1 1 39.552 50.304l-161.696 127.04a31.776 31.776 0 0 1-19.744 6.848z"
                  p-id="2122"
                ></path>
                <path
                  d="M667.552 218.24a31.84 31.84 0 0 1-19.744-6.848l-155.552-122.24a31.936 31.936 0 0 1-5.376-44.928 31.968 31.968 0 0 1 44.928-5.376l155.552 122.24a31.936 31.936 0 0 1-19.808 57.152zM960 448a31.84 31.84 0 0 1-19.744-6.848l-126.688-99.552a31.936 31.936 0 0 1-5.376-44.928 31.904 31.904 0 0 1 44.928-5.376l126.688 99.552A31.936 31.936 0 0 1 960 448zM160.032 896a32 32 0 0 1-19.424-57.472l257.92-196.128a32 32 0 1 1 38.752 50.912l-257.92 196.128a31.552 31.552 0 0 1-19.328 6.56zM863.968 896a31.712 31.712 0 0 1-19.328-6.528l-257.92-196.128a32 32 0 1 1 38.752-50.912l257.92 196.128A32 32 0 0 1 863.968 896z"
                  p-id="2123"
                ></path>
                <path
                  d="M512 768.448a31.872 31.872 0 0 1-18.624-5.984l-448-320.448a32 32 0 0 1 37.216-52.064L512 697.088l429.376-307.136a32 32 0 1 1 37.216 52.064l-448 320.448a31.68 31.68 0 0 1-18.592 5.984z"
                  p-id="2124"
                ></path>
                <path
                  d="M832 516.832a32 32 0 0 1-32-32V224H224v260.832a32 32 0 0 1-64 0V224c0-35.296 28.704-64 64-64h576c35.296 0 64 28.704 64 64v260.832a32 32 0 0 1-32 32z"
                  p-id="2125"
                ></path>
                <path
                  d="M704 352H320a32 32 0 0 1 0-64h384a32 32 0 0 1 0 64zM704 480H320a32 32 0 0 1 0-64h384a32 32 0 0 1 0 64z"
                  p-id="2126"
                ></path>
              </svg>
              <span class="num-after-icon">{{ row.openNum }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('email.replyNum')"
          align="center"
          min-width="70px"
        >
          <template slot-scope="{ row }">
            <span class="count_icon">
              <!-- @click="handleGetPageviews(row.pageviews)" -->
              <i class="el-icon-chat-round"
                ><span class="num-after-icon">{{ row.replyNum }}</span></i
              ></span
            >
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('email.submitTime')"
          width="150px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span v-time="row.createdAt"></span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('table.actions')"
          align="center"
          min-width="120"
        >
          <template slot-scope="{ row, $index }">
            <el-button-group>
              <!-- <el-tooltip
                class="item"
                effect="light"
                content="编辑"
                placement="top"
                v-if="row.state===1 && row.type===1"
              >
                <el-button
                  class="!border-orange-500 !text-orange-500"
                  size="mini"
                  @click="handleChangeState(row.id)"
                  icon="el-icon-edit"
                />
              </el-tooltip> -->
              <el-tooltip
                class="item"
                effect="light"
                :content="$t('email.EditSendTime')"
                placement="top"
                v-if="
                  (row.state === 'UN_SUBMIT' || row.state === 'SUBMITTED') &&
                  row.type === 'SERVER'
                "
              >
                <el-button
                  class="!border-orange-500 !text-orange-500"
                  size="mini"
                  @click="handleChangeTimingTransmission(row)"
                  icon="el-icon-timer"
                />
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="light"
                :content="$t('email.submitSend')"
                placement="top"
                v-if="row.state === 'UN_SUBMIT' && row.type === 'SERVER'"
              >
                <el-button
                  class="!border-orange-500 !text-orange-500"
                  size="mini"
                  icon="el-icon-s-promotion"
                  @click="handleChangeState(row.id)"
                />
              </el-tooltip>
              <!-- <el-button
              class="!border-orange-500 !text-orange-500"
              size="mini"
              @click="handleCopy(row)"
            >
              克隆
            </el-button> -->
              <el-tooltip
                class="item"
                effect="light"
                :content="$t('email.exportEmail')"
                placement="top"
              >
                <el-button
                  class="!border-orange-500 !text-orange-500"
                  size="mini"
                  icon="el-icon-download"
                  @click="handleExportEmail(row.addresseeObj)"
                />
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="light"
                :content="$t('email.cancelTask')"
                placement="top"
              >
                <el-button
                  class="!border-orange-500 !text-orange-500"
                  size="mini"
                  icon="el-icon-delete"
                  @click="handleCancelEmailMarketingTask(row)"
                />
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
      >
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="tempArticleData"
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left: 50px"
        >
          <el-form-item :label="$t('table.type')" prop="type">
            <el-select v-model="tempArticleData.type" class="filter-item">
              <el-option
                v-for="item in calendarTypeOptions"
                :key="item.key"
                :label="item.displayName"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('table.date')" prop="timestamp">
            <el-date-picker
              v-model="tempArticleData.timestamp"
              type="datetime"
            />
          </el-form-item>
          <el-form-item :label="$t('table.title')" prop="title">
            <el-input v-model="tempArticleData.title" />
          </el-form-item>
          <el-form-item :label="$t('table.status')">
            <el-select v-model="tempArticleData.status" class="filter-item">
              <el-option
                v-for="item in statusOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('table.importance')">
            <el-rate
              v-model="tempArticleData.importance"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              :max="3"
              style="margin-top: 8px"
            />
          </el-form-item>
          <el-form-item :label="$t('table.remark')">
            <el-input
              v-model="tempArticleData.abstractContent"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            {{ $t('table.cancel') }}
          </el-button>
          <el-button
            type="primary"
            @click="dialogStatus === 'create' ? createData() : updateData()"
          >
            {{ $t('table.confirm') }}
          </el-button>
        </div>
      </el-dialog>

      <el-dialog
        :visible.sync="dialogPageviewsVisible"
        title="Reading statistics"
      >
        <el-table
          :data="pageviewsData"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column prop="key" label="Channel" />
          <el-table-column prop="pageviews" label="Pageviews" />
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogPageviewsVisible = false">{{
            $t('table.confirm')
          }}</el-button>
        </span>
      </el-dialog>
      <showSendDataTracking
        :show.sync="showSendDataTrackingVisible"
        :rowId="sendDataTrackingId"
      />
      <edit-timing-transmission
        :show.sync="showEditTimingTransmissionVisible"
        :timingTransmission="timingTransmissionDialog"
        :id="id"
      />
      <VerifyEmail :show.sync="showVerifyEmailVisible" />
      <pagination
        v-show="list.totalCount > 0"
        :total="list.totalCount"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        :page-sizes="pageSize"
      />
    </div>
  </el-scrollbar>
</template>
<style scoped>
.state_unsubmit {
  color: #609cd3;
}

.state_unsubmit > i {
  font-size: 20px;
  margin-right: 5px;
}

.state_submit {
  color: plum;
}
.state_submit > i {
  font-size: 20px;
  margin-right: 5px;
}

.state_cancel {
  color: orange;
}
.state_cancel > i {
  font-size: 20px;
  margin-right: 5px;
}

.state_complete {
  color: green;
}
.state_complete > i {
  font-size: 20px;
  margin-right: 5px;
}

.count_icon > i {
  @apply text-orange-500;
  font-size: 20px;
  margin-right: 5px;
}

.num-after-icon {
  color: black;
  margin-left: 5px;
  font-size: 14px;
  font-family: 'element-icons' !important;
}
</style>
<script lang="ts">
import { Form } from 'element-ui'
import { cloneDeep } from 'lodash'
import {
  getPageviews,
  createArticle,
  updateArticle,
  defaultArticleData,
} from '@/api/articles'
import { exportJson2Excel } from '@/utils/excel'
import { formatJson } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'
import showSendDataTracking from './showSendDataTracking.vue'
import VerifyEmail from './verifyEmail.vue'
import DateSelector from '@/components/Public/dateSelector.vue'
import { getAction, postAction } from '@/api/common'
import editTimingTransmission from './editTimingTransmission.vue'
import gql from 'graphql-tag'
const calendarTypeOptions = [
  { key: 'CN', displayName: 'China' },
  { key: 'US', displayName: 'USA' },
  { key: 'JP', displayName: 'Japan' },
  { key: 'EU', displayName: 'Eurozone' },
]
// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce(
  (acc: { [key: string]: string }, cur) => {
    acc[cur.key] = cur.displayName
    return acc
  },
  {}
) as { [key: string]: string }
export default {
  name: 'EmailMarketingTaskIndex',
  components: {
    DateSelector,
    Pagination,
    VerifyEmail,
    showSendDataTracking,
    editTimingTransmission,
  },
  filters: {
    typeFilter: (type: string) => {
      return calendarTypeKeyValue[type]
    },
  },
  props: {
    ids: {},
  },
  apollo: {
    list: {
      query: gql`
        query GetEmailMarketings(
          $skip: Int!
          $take: Int!
          $where: EmailMarketingFilterInput
        ) {
          emailMarketings(
            take: $take
            skip: $skip
            order: { id: DESC }
            where: $where
          ) {
            totalCount
            items {
              id
              title
              type
              submitNum
              sendingNum
              openNum
              replyNum
              state
              createdAt
              addresseeObj {
                addressee
                name
              }
            }
          }
        }
      `,
      variables() {
        const take = this.listQuery.limit
        const skip = Math.max(this.listQuery.page - 1, 0) * take
        let where: any = {}
        if (this.listQuery.title) {
          where.title = { contains: this.listQuery.title }
        }
        if (this.listQuery.state) {
          where.state = { eq: this.listQuery.state }
        }
        if (this.listQuery.createdAt && this.listQuery.createdAt.length == 2) {
          let endDate = new Date(this.listQuery.createdAt[1])
          endDate.setDate(endDate.getDate() + 1)
          where.createdAt = {
            gte: new Date(this.listQuery.createdAt[0]),
            lte: endDate,
          }
        }
        if (this.ids) {
          where.id = { in: this.ids }
        }
        return {
          skip,
          take,
          where,
        }
      },
      update: (data) => data.emailMarketings,
    },
  },
  data() {
    return {
      pageSize: [15, 30, 60, 100, 200, 300],
      tableKey: 0,
      list: { totalCount: 0, items: [] },
      id: 0,
      listLoading: false,
      dialogFormVisible: false,
      showVerifyEmailVisible: false,
      emailSendFreeVisible: false,
      showSendDataTrackingVisible: false,
      showEditTimingTransmissionVisible: false,
      sendDataTrackingId: 0,
      timingTransmissionDialog: '2021-01-01 00:00:00',
      listQuery: {
        page: 1,
        limit: 15,
        total: 0,
        title: undefined,
        state: undefined,
        createdAt: undefined,
        ids: undefined,
      },
      value2: '',
      stateOptions: [
        {
          key: 'UN_SUBMIT',
          label: this.$t('email.notSubmit'),
          icon: 'el-icon-edit-outline',
          class: 'state_unsubmit',
        },
        {
          key: 'SUBMITTED',
          label: this.$t('email.submited'),
          icon: 'el-icon-circle-check',
          class: 'state_submit',
        },
        {
          key: 'CANCELED',
          label: this.$t('email.canceled'),
          icon: 'el-icon-circle-close',
          class: 'state_cancel',
        },
        {
          key: 'COMPLETED',
          label: this.$t('email.done'),
          icon: 'el-icon-finished',
          class: 'state_complete',
        },
      ],
      calendarTypeOptions: calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' },
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      visible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create',
      },
      dialogPageviewsVisible: false,
      pageviewsData: [],
      rules: {
        type: [
          { required: true, message: 'type is required', trigger: 'change' },
        ],
        timestamp: [
          {
            required: true,
            message: 'timestamp is required',
            trigger: 'change',
          },
        ],
        title: [
          { required: true, message: 'title is required', trigger: 'blur' },
        ],
      },
      downloadLoading: false,
      tempArticleData: defaultArticleData,
    }
  },
  created() {
    this.listQuery.ids = this.ids ?? undefined
  },
  methods: {
    async handleShowSendDataTracking(value: number) {
      this.showSendDataTrackingVisible = true
      // console.log('value', value)
      this.sendDataTrackingId = value
    },
    async handleVerifyEmail() {
      this.showVerifyEmailVisible = true
    },
    handleChangeState(id: Number) {
      this.listLoading = true
      this.$confirm(
        this.$t('email.confirmSubmitMarketingTask'),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning',
        }
      )
        .then(() => {
          getAction('', `EmailMarketing/ChangeState?id=${id}`).then(
            (res: any) => {
              if (res.code === 20000) {
                this.$message({
                  message: this.$t('email.submitSendSuccessfully'),
                  type: 'success',
                })
                this.refresh()
              } else {
                this.$message({
                  message: this.$t('email.submitSendFailed'),
                  type: 'warning',
                })
              }
            }
          )
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    async handleEmailSendFree() {
      this.$router.push('/email/emailSendFree/add?fromPage=Index')
    },
    async createMarketingTaskByServer() {
      this.$router.push('/email/emailServerSend/add?fromPage=Index')
    },
    handleModifyStatus(row: any, status: string) {
      this.$message({
        message: this.$t('common.operationSuccess'),
        type: 'success',
      })
      row.status = status
    },
    resetTempArticleData() {
      this.tempArticleData = cloneDeep(defaultArticleData)
    },
    handleCreate() {
      this.resetTempArticleData()
      // this.dialogStatus = 'create'
      // this.createMarketingTaskVisible = true
      // this.$nextTick(() => {
      //   (this.$refs.dataForm as Form).clearValidate()
      // })
    },
    createData() {
      ;(this.$refs.dataForm as Form).validate(async (valid) => {
        if (valid) {
          const articleData = this.tempArticleData
          articleData.id = Math.round(Math.random() * 100) + 1024 // mock a id
          articleData.author = 'vue-typescript-admin'
          const { data } = await createArticle({ article: articleData })
          data.article.timestamp = Date.parse(data.article.timestamp)
          this.list.unshift(data.article)
          this.dialogFormVisible = false
          this.$notify({
            title: this.$t('common.success'),
            message: this.$t('common.addSuccessfully'),
            type: 'success',
            duration: 2000,
          })
        }
      })
    },
    handleUpdate(row: any) {
      this.tempArticleData = Object.assign({}, row)
      this.tempArticleData.timestamp = +new Date(this.tempArticleData.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        ;(this.$refs.dataForm as Form).clearValidate()
      })
    },
    updateData() {
      ;(this.$refs.dataForm as Form).validate(async (valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.tempArticleData)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          const { data } = await updateArticle(tempData.id, {
            article: tempData,
          })
          const index = this.list.findIndex((v) => v.id === data.article.id)
          this.list.splice(index, 1, data.article)
          this.dialogFormVisible = false
          this.$notify({
            title: this.$t('common.success'),
            message: this.$t('common.updateSuccessfully'),
            type: 'success',
            duration: 2000,
          })
        }
      })
    },
    handleDelete(row: any, index: number) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000,
      })
      this.list.splice(index, 1)
    },
    async handleGetPageviews(pageviews: string) {
      const { data } = await getPageviews({ pageviews })
      this.pageviewsData = data.pageviews
      this.dialogPageviewsVisible = true
    },
    handleDownload() {
      this.downloadLoading = true
      const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
      const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
      const data = formatJson(filterVal, this.list)
      exportJson2Excel(tHeader, data, 'table-list')
      this.downloadLoading = false
    },
    refresh() {
      this.$apollo.queries.list.refresh()
    },
    handleFilter() {
      // console.log('search')
      this.refresh()
    },
    async handleExportEmail(addresseeObj: any) {
      // console.log(addresseeObj)
      // const emailListTemp = addresseeObj.map((m: any) => m.addressee)
      this.downloadEmailTxt(addresseeObj)
    },
    async downloadEmailTxt(addresseeObj: any) {
      let str = ''
      addresseeObj.forEach((item: any) => {
        str += item.addressee + '|' + item.name + '\r\n'
      })
      const export_blob = new Blob([str])
      const save_link = document.createElement('a')
      save_link.href = window.URL.createObjectURL(export_blob)
      save_link.download = this.$t('common.export') + '.txt'
      this.fakeClick(save_link)
    },
    async fakeClick(obj: any) {
      const ev = document.createEvent('MouseEvents')
      ev.initMouseEvent(
        'click',
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null
      )
      obj.dispatchEvent(ev)
    },
    handleChangeTimingTransmission(row: any) {
      this.showEditTimingTransmissionVisible = true
      this.id = row.id
      this.timingTransmissionDialog = row.timingTransmission
    },
    handleCancelEmailMarketingTask(row: any) {
      this.$confirm(
        this.$t('email.confirmCancelMarketingTask'),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning',
        }
      )
        .then(() => {
          if (row.state === 1 || row.state === 2) {
            getAction(
              {},
              `EmailMarketing/CancelEmailMarketingTask?id=${row.id}`
            )
              .then(() => {
                this.$message({
                  message: this.$t('email.taskCanceled'),
                  type: 'success',
                })
              })
              .then(() => {
                this.refresh()
              })
          } else {
            this.$message({
              message: this.$t('email.currentStateCantDoThis'),
              type: 'warning',
            })
            return false
          }
        })
        .catch((e) => {
          // console.log('已取消操作')
        })
    },
  },
}
</script>
